﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.IO;
using System.Threading;

namespace ChatClient
{
    class Client
    {
        string host;
        int port;
        bool portValide;
        string pseudo;
        Socket socket;
        StreamReader reader;
        StreamWriter writer;
        Thread t_receiver;

        public Client()
        {
            Console.WriteLine("Pseudo :");
            pseudo = Console.ReadLine();

            Console.WriteLine("Serveur :");
            host = Console.ReadLine();


            while (!portValide)
            {
                try
                {
                    Console.WriteLine("port :");
                    port = Convert.ToInt16(Console.ReadLine());
                    portValide = true;
                }
                catch
                {
                    Console.WriteLine("\n" + "port est un nombre entier" + "\n");
                }
            }

            Connect(host, port);
            Read();
        }

        public void Connect(string host, int port)
        {
            socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            try
            {
                Stream s = new NetworkStream(socket);
                reader = new StreamReader(s);
                writer = new StreamWriter(s);

                socket.Connect(host, port);
                writer.WriteLine(pseudo + "\n");
                writer.Flush();
                Console.WriteLine("Bienvenu " + pseudo + "!");
            }
            catch (IOException exc)
            {
                Console.WriteLine("\n" + "Erreur : " + exc);
                Close();
            }
        }

        public void Send(string message)
        {
            writer.WriteLine(message);
            writer.Flush();
        }

        public void StartTalk()
        {
            while (true)
            {
                Send(Console.ReadLine());  
            }
        }

        public void Read()
        {
            t_receiver = new Thread(ReaderThread);
        }

        public void ReaderThread()
        {
            try
            {
                StartTalk();
            }
            catch (IOException exc)
            {
                Console.WriteLine("\n" + "Erreur : " + exc);
                Close();
            }
        }

        public void Close()
        {
            Console.WriteLine("\n" + "MyChat va fermer" + "\n\n" + "Appuyez sur la touche Entrée...");
            Console.ReadLine();
            socket.Close();
            if (t_receiver != null)
                t_receiver.Abort();
        }
    }
}
